import router from "./index.ts";
import { ElMessage } from "element-plus";
import { routestore } from "@/store/modules/permission";
import { getuserlist } from "@/request/routes";
import { getrouteslist } from "@/Hook/getroutes";
import { storeToRefs } from "pinia";
// 路由守卫
// 只要进入到某个路由就会执行此方法
// 路由守卫
// let registerRouteFresh = true;
let route = useRoute();

router.beforeEach(async (to, from, next) => {
  let token = localStorage.getItem("token");
  console.log(route);
  const routes = routestore();
  let { routeslist } = storeToRefs(routes);
  if (token) {
    var routesdata = "";
    await getuserlist().then(({ userinfo: { route_list } }) => {
      console.log("res",JSON.parse(route_list),routeslist._object.routeslist);
      routesdata = getrouteslist(JSON.parse(route_list));
    });
    routes.addroutes(routesdata)
// console.log("routeslist",routeslist);

    //  如果首次或者刷新界面，next(...to, replace: true)会循环遍历路由，如果to找不到对应的路由那么他会再执行一次beforeEach((to, from, next))直到找到对应的路由，我们的问题在于页面刷新以后异步获取数据，直接执行next()感觉路由添加了但是在next()之后执行的，所以我们没法导航到相应的界面。这里使用变量registerRouteFresh变量做记录，直到找到相应的路由以后，把值设置为false然后走else执行next(),整个流程就走完了，路由也就添加完了。
    // if (!routeslist._object.routeslist) {
    if (!to.name) {
        if (!routeslist._object.routeslist.findIndex((i) => i.path === to.path) !== -1) {
            next({ ...to, replace: true });
        }else{
          next("/404")
        }
      } else {
        next();
      }
      // }
  } else {
    // 未登录
    if (to.path == "/login" || to.path == "/register") {
      next();
      return;
    }
    ElMessage({
      message: "您当前未登录,请进行登录",
      type: "warning",
    });
    next("/login");
  }
});
